package com.easyOrder.core.comm;

import com.easyOrder.core.dynamics.config.ConfigComponent;
import com.easyOrder.core.dynamics.config.ConfigTypes;
import com.easyOrder.core.mongo.log.LogComponent;
import com.easyOrder.core.mongo.log.Visit;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.slf4j.MDC;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

//import org.aspectj.lang.JoinPoint;
//import org.aspectj.lang.annotation.After;
//import org.aspectj.lang.annotation.AfterReturning;
//import org.aspectj.lang.annotation.AfterThrowing;
//import org.aspectj.lang.annotation.Before;

/**
 * 日志切面
 *
 * @author yanbin
 */
@Aspect
@Component
public class TimeOutLogAspectJ {

    @Autowired
    LogComponent logService;

    @Autowired
    ConfigComponent configs;

    private String configDefaultValue = "2000";

    private static final Logger logger = Logger
            .getLogger(TimeOutLogAspectJ.class);

    public TimeOutLogAspectJ() {

    }


//    @Pointcut("execution(* com.meallink..*.*(..))")
//    private void anyMethod() {
//
//    }
//
//    @Pointcut("execution(public * com.meallink.web.action..*.*(..))")
//    private void actionMethod() {
//
//    }

    /**
     * 定义前置通知
     * @param joinpoint
     */
//	@Before("anyMethod()")
//	public void myBeforeAdvice(JoinPoint joinpoint) {
//		String classAndMethod = joinpoint.getTarget().getClass().getName()
//				+ "类的" + joinpoint.getSignature().getName();
//		logger.info("前置通知:" + classAndMethod + "方法开始执行！");
//	}

    /**
     * 定义后置通知
     * @param joinpoint
     */
//	@AfterReturning("anyMethod()")
//	public void myAfterReturningAdvice(JoinPoint joinpoint) {
//		String classAndMethod = joinpoint.getTarget().getClass().getName()
//				+ "类的" + joinpoint.getSignature().getName();
//		logger.info("后置通知:" + classAndMethod + "方法执行正常结束！");
//	}

    /**
     * 定义异常通知
     *
     * @param joinpoint
     * @param e
     */
//    @AfterThrowing(pointcut = "actionMethod()", throwing = "e")
//    public void actionAfterThrowingAdvice(JoinPoint joinpoint, java.lang.Exception e) {
//        writeLog(e);
//    }
//
//    private void writeLog(java.lang.Exception e) {
//        logger.error(e, e);
//        String exceptionTrace = JsonExceptionWrapper.getStackTrace(e);
//        JsonExceptionWrapper result = new JsonExceptionWrapper(e);
//        logService.insertExcept(result, exceptionTrace);
//    }

    /**
     * 定义最终通知
     * @param joinpoint
     */
//	@After("anyMethod()")
//	public void myAfterAdvice(JoinPoint joinpoint) {
//		String classAndMethod = joinpoint.getTarget().getClass().getName()
//				+ "类的" + joinpoint.getSignature().getName();
//		logger.info("最终通知:" + classAndMethod + "方法执行结束！");
//	}

    /**
     * 定义环绕通知
     *
     * @param pjp
     * @return
     * @throws Throwable
     */
    @Around("execution(public * com.easyOrder.web.action*..*.*(..))")
    public Object myAroundAdvice(ProceedingJoinPoint pjp) throws Throwable {
        long timeSpan = 2000L;
        long time;
        Object result = null;
        long beginTime = System.currentTimeMillis();
        try {
            result = pjp.proceed();
        } catch (Throwable throwable) {
            throw throwable;
        }
        long endTime = System.currentTimeMillis();
            time = endTime - beginTime;
        String configValue = configs.getValue(ConfigTypes.visitTimeOut, configDefaultValue);
        if (StringUtils.isNumeric(configValue)) {
            timeSpan = Long.parseLong(configValue);
        }

        if (time > timeSpan) {
            Visit visit = new Visit();
            if (MDC.get("ip") != null) {
                visit.setIp(MDC.get("ip"));
            }
            if (null != MDC.get("userId")) {
                visit.setUserId(MDC.get("userId"));
            }
            if (null != MDC.get("url")) {
                visit.setUrl(MDC.get("url"));
            }
            if (null != MDC.get("url_body")) {
                visit.setBody(MDC.get("url_body"));
            }
            visit.setMethod(pjp.getTarget().getClass().getName());
            visit.setSignatureName(pjp.getSignature().getName());
            //visit.setParameter(Arrays.toString(pjp.getArgs()));
            visit.setTimeSpan(time);
            logService.insertVisit(visit);
        }
        return result;
    }
}